'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'

interface FieldData {
  id: number
  field_name: string
  field_description: string
  data_source: string
  data_type: string
  measurement_unit: string
  is_required: boolean
  example_description: string
}

export default function DebugAllFieldsPage() {
  const [fields, setFields] = useState<FieldData[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const loadFields = async () => {
      try {
        const response = await fetch('/api/field-metadata?tableName=table_c2')
        const data = await response.json()
        
        if (data.success) {
          setFields(data.data.fields || [])
        } else {
          setError(data.error || '加载失败')
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '加载失败')
      } finally {
        setLoading(false)
      }
    }

    loadFields()
  }, [])

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'R': 'bg-red-100 text-red-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  const getDataSourceName = (source: string) => {
    const names: Record<string, string> = {
      'P': '采购',
      'E': '设计',
      'M': '制造',
      'O': '运维',
      'C': '施工',
      'R': '运行'
    }
    return names[source] || source
  }

  if (loading) {
    return <div className="p-8">加载中...</div>
  }

  if (error) {
    return <div className="p-8 text-red-600">错误: {error}</div>
  }

  // 按数据来源分组
  const fieldsBySource = fields.reduce((acc, field) => {
    if (!acc[field.data_source]) {
      acc[field.data_source] = []
    }
    acc[field.data_source].push(field)
    return acc
  }, {} as Record<string, FieldData[]>)

  const allSources = Object.keys(fieldsBySource).sort()

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">所有字段调试页面</h1>
      
      {/* 总体统计 */}
      <Card>
        <CardHeader>
          <CardTitle>字段统计</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="text-center">
              <div className="text-2xl font-bold">{fields.length}</div>
              <div className="text-sm text-gray-600">总字段数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold">{allSources.length}</div>
              <div className="text-sm text-gray-600">数据来源数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold">{fields.filter(f => f.is_required).length}</div>
              <div className="text-sm text-gray-600">必填字段</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold">{fields.filter(f => !f.is_required).length}</div>
              <div className="text-sm text-gray-600">可选字段</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 按数据来源分组显示 */}
      <div className="space-y-6">
        {allSources.map(source => {
          const sourceFields = fieldsBySource[source]
          return (
            <Card key={source}>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Badge className={getDataSourceColor(source)}>
                    {source}
                  </Badge>
                  <span>{getDataSourceName(source)}专业字段</span>
                  <span className="text-sm text-gray-500">({sourceFields.length} 个字段)</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>ID</TableHead>
                      <TableHead>字段名称</TableHead>
                      <TableHead>描述</TableHead>
                      <TableHead>数据类型</TableHead>
                      <TableHead>计量单位</TableHead>
                      <TableHead>是否必填</TableHead>
                      <TableHead>示例</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sourceFields.map(field => (
                      <TableRow key={field.id}>
                        <TableCell>{field.id}</TableCell>
                        <TableCell className="font-medium">{field.field_name}</TableCell>
                        <TableCell className="text-sm text-gray-600">{field.field_description}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{field.data_type}</Badge>
                        </TableCell>
                        <TableCell>{field.measurement_unit || '-'}</TableCell>
                        <TableCell>
                          {field.is_required ? (
                            <Badge variant="destructive" className="text-xs">必填</Badge>
                          ) : (
                            <Badge variant="secondary" className="text-xs">可选</Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-gray-500">
                          {field.example_description || '-'}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )
        })}
      </div>

      {/* 原始数据 */}
      <Card>
        <CardHeader>
          <CardTitle>原始API响应</CardTitle>
        </CardHeader>
        <CardContent>
          <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto max-h-96">
            {JSON.stringify(fields, null, 2)}
          </pre>
        </CardContent>
      </Card>
    </div>
  )
}
